from django.shortcuts import render,HttpResponse
from . import models
import json
import urllib.request
from User.models import User

# Create your views here.
def ProductDetailView(request):
    try:
        if(request.method == 'GET'):
            json_result = json.loads(request.body.decode())
            product_id = json_result.get('product_id')
            if (models.Product.objects.filter(PID = product_id).exists()):
    
                #数据库查询
                product = models.Product.objects.get(PID = product_id)
                product_name = product.ProdName
                product_intro = product.ProdIntro
                seller = product.ProdSellerID
                product_sellerid = seller.UID
                product_sellername = seller.UserName
                product_image1 = product.ProdImage1
                product_image2 = product.ProdImage2
                product_image3 = product.ProdImage3
                product_tag1 = product.ProdTag1
                product_tag2 = product.ProdTag2
                product_tag3 = product.ProdTag3
                product_tag4 = product.ProdTag4
                product_tag5 = product.ProdTag5
                
                # 向前端发送数据
                result = {
                    'product_name':product_name,
                    'product_intro':product_intro,
                    'product_sellerid':product_sellerid,
                    'product_sellername':product_sellername,
                    'product_image1':product_image1,
                    'product_image2':product_image2,
                    'product_image3':product_image3,
                    'product_tag1':product_tag1,
                    'product_tag2':product_tag2,
                    'product_tag3':product_tag3,
                    'product_tag4':product_tag4,
                    'product_tag5':product_tag5
                }
                return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")
    
            else:
                return HttpResponse("Fail(id:1)") # pid不存在
    except:
        return HttpResponse("Fail(id:0)") # 未知错误

def ProductSetView(request):
    try:
        if (request.method == 'POST'):
            json_result = json.loads(request.body.decode())
            product_name = json_result.get('product_name')
            product_intro = json_result.get('product_intro')
            product_sellerid = json_result.get('product_sellerid')
            seller = User.objects.get(UID = product_sellerid)
            product_image1 = json_result.get('product_image1')
            product_image2 = json_result.get('product_image2')
            product_image3 = json_result.get('product_image3')
            product_tag1 = json_result.get('product_tag1')
            product_tag2 = json_result.get('product_tag2')
            product_tag3 = json_result.get('product_tag3')
            product_tag4 = json_result.get('product_tag4')
            product_tag5 = json_result.get('product_tag5')
            # 为商品分配唯一id
            pid = "P" + str(models.Product.objects.count()).zfill(15)
            
            #下载图片和存储图片
            file_path = '/www/wwwroot/TsinghuaMarket/media/images/'
            if not (product_image1 == ''):
                filesuffix1 = pid + 'ProdImage1.jpg'
                filename1 = file_path + filesuffix1
                urllib.request.urlretrieve(product_image1, filename=filename1)
                product_image1 = 'http//47.94.130.28:8000/media/images' + filesuffix1
            if not (product_image2 == ''):
                filesuffix2 = pid + 'ProdImage2.jpg'
                filename2 = file_path + filesuffix2
                urllib.request.urlretrieve(product_image2, filename=filename2)
                product_image2 = 'http//47.94.130.28:8000/media/images' + filesuffix2
            if not (product_image3 == ''):
                filesuffix3 = pid + 'ProdImage3.jpg'
                filename3 = file_path + filesuffix3
                urllib.request.urlretrieve(product_image3, filename=filename3)
                product_image3 = 'http//47.94.130.28:8000/media/images' + filesuffix3
            
            product = models.Product(PID = pid, ProdName=product_name, ProdIntro=product_intro, 
                ProdSellerID=seller, ProdImage1=product_image1, 
                ProdImage2=product_image2, ProdImage3=product_image3, 
                ProdTag1=product_tag1, ProdTag2=product_tag2, ProdTag3=product_tag3, 
                ProdTag4=product_tag4, ProdTag5=product_tag5)
            product.save()
            return HttpResponse("Success")
    except:
        return HttpResponse("Fail(id:0)") # 未知错误

def SearchView(request):
    #try:
    if (request.method == 'RETRIEVE'):
        
        # 获取前端返回数据
        json_result = json.loads(request.body.decode())
        keyword = json_result.get('keyword')
        from django.db.models import Q
        if (models.Product.objects.filter(Q(ProdName__contains=keyword) | Q(ProdIntro__contains=keyword)).exists()):
            
            # 从数据库提取搜索到的商品列表
            pList = models.Product.objects.filter(Q(ProdName__contains=keyword) | Q(ProdIntro__contains=keyword))
            
            result = ''
            for p in pList:
                product_id = p.PID
                product_name = p.ProdName
                product_image1 = p.ProdImage1
                product_image2 = p.ProdImage2
                product_image3 = p.ProdImage3
                
                p_dict = {
                    'product_id': product_id,
                    'product_name': product_name,
                    'product_image1': product_image1,
                    'product_image2': product_image2,
                    'product_image3': product_image3
                }                    
                result = result + json.dumps(p_dict, ensure_ascii=False)
                               
            #向前端发送数据
            return HttpResponse(result, content_type="application/json,charset=utf-8")
        else:
            return HttpResponse("Fail(id:1)")

    #except:
        #return HttpResponse("Fail(id:0)") # 未知错误
        
def ProductListView(request):
    if (request.method == 'RETRIEVE'):
        json_result = json.loads(request.body.decode())
        #tags = []
        tag1 = json_result.get('product_tag1')
        #tag2 = json_result.get('product_tag2')
        #tag3 = json_result.get('product_tag3')
        #tag4 = json_result.get('product_tag4')
        #tag5 = json_result.get('product_tag5')
        #tags = [tag1, tag2, tag3, tag4, tag5]
        productList1 = list(models.Product.objects.filter(ProdTag1 = tag1))
        productList2 = list(models.Product.objects.filter(ProdTag2 = tag1))
        productList3 = list(models.Product.objects.filter(ProdTag3 = tag1))
        productList4 = list(models.Product.objects.filter(ProdTag4 = tag1))
        productList5 = list(models.Product.objects.filter(ProdTag5 = tag1))
        productList = list(set(productList1+productList2+productList3+productList4+productList5))
        
        result = ''
        for product in productList:
            product_id = product.PID
            product_name = product.ProdName
            product_image1 = product.ProdImage1
            product_image2 = product.ProdImage2
            product_image3 = product.ProdImage3
            product_dict = {
                'product_id':product_id,
                'product_name':product_name,
                'product_image1': product_image1,
                'product_image2': product_image2,
                'product_image3': product_image3,
            }
            result = result + json.dumps(product_dict, ensure_ascii=False)
        return HttpResponse(result, content_type="application/json,charset=utf-8")
        
def TagList(request):
    if (request.method == 'GET'):
        results = json.loads(json.dumps({}))
        
        categories = models.Tag.objects.values("TagCategory").distinct()

        i = 0
        for tagcategory in categories:
            category = tagcategory["TagCategory"]
            children = {}
            tags = models.Tag.objects.filter(TagCategory=category)
            for tag in tags:
                tag_result = {
                    'tag_name':tag.TagName,
                    'img_src':tag.TagImage,
                }
                children[tag.TID] = tag_result
            category_result = {
                'cate_name':category,
                'children':children,
            }
            results[i] = category_result
            i = i + 1
        return HttpResponse(json.dumps(results, ensure_ascii=False), content_type="application/json,charset=utf-8")
        
def TagListSelect(request):
    if (request.method == 'GET'):
        majortags = models.Tag.objects.filter(TagMajor=True)
        results = json.loads(json.dumps({}))
        for tag in majortags:
            tid = tag.TID
            tag_name = tag.TagName
            image_src = tag.TagImage
            tag_result = {
                'tag_name':tag_name,
                'image_src':image_src,
            }
            results[tid] = tag_result
        return HttpResponse(json.dumps(results, ensure_ascii=False), content_type="application/json,charset=utf-8")